<template>
  <div class="qaBox">
    <el-row
      type="flex"
      justify="space-between"
      class="boxShadow"
      style="width: 100%; height: 18%"
    >
      <el-col
        style="width: 24%"
        v-for="item in cardBox"
        :key="item.id"
      >
        <cardBox :cardBox="item" />
      </el-col>
    </el-row>
    <el-row
      style="width: 100%; height: 82%"
      class="boxShadow"
    >
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        style="margin-bottom: 10px"
      >
        <el-col
          :lg="7"
          style="display: flex; align-items: center"
        >
          任务状态：
          <el-select
            style="flex: 1"
            v-model="taskType"
            placeholder="请选择"
          >
            <el-option
              label="待开始"
              :value="0"
            >
            </el-option>
            <el-option
              label="进行中"
              :value="1"
            >
            </el-option>
            <el-option
              label="已完成"
              :value="2"
            >
            </el-option>
            <el-option
              label="已逾期"
              :value="3"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col
          :lg="7"
          style="display: flex; align-items: center"
          >搜索：
          <el-input
            style="flex: 1"
            v-model="key"
            placeholder="任务名称"
          ></el-input>
        </el-col>
        <el-col
          :lg="7"
          style="display: flex; align-items: center"
          >任务日期：
          <el-date-picker
            v-model="date"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-col>
      </el-row>
      <el-row
        style="margin-bottom: 10px"
        type="flex"
        justify="start"
      >
        <el-col :span="12">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="toAddHandler"
          >
            新增</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-download"
            @click="batchExport"
          >
            批量导出</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="setTask"
          >
            任务设置</el-button
          >
        </el-col>
        <el-col
          :lg="12"
          style="text-align: right"
        >
          <el-button
            type="primary"
            @click="searchHandler"
            >查询</el-button
          ><el-button
            plain
            @click="NewSearch"
            >重置</el-button
          >
        </el-col>
      </el-row>
      <el-row class="tableBox">
        <el-table
          :data="renderData"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#606266', color: '#fff' }"
          height="450"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          >
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="55"
            align="center"
          />

          <el-table-column
            prop="taskType"
            label="任务状态"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.taskType == 0"
                type="info"
                >待开始</el-tag
              >
              <el-tag
                v-else-if="scope.row.taskType == 1"
                type="warning"
                >进行中</el-tag
              >
              <el-tag
                v-else-if="scope.row.taskType == 2"
                type="success"
                >已完成</el-tag
              >
              <el-tag
                v-else
                type="danger"
                >已逾期</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="任务名称"
            align="center"
            min-width="120"
          >
          </el-table-column>
          <el-table-column
            prop="type"
            label="任务类型"
            min-width="120"
            align="center"
          >
            <template slot-scope="scope">
              <p
                v-for="(el, index) in scope.row.taskTypes"
                :key="index"
              >
                {{ index + 1 }}. {{ el.name }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            prop="content"
            label="任务内容"
            align="center"
            min-width="150"
          />
          <el-table-column
            prop="responsibleUser"
            label="负责人"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <p>
                {{ scope.row.responsibleUser.name }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            prop="createUserName"
            label="发起人"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="carbonCopyUsers"
            label="抄送人"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <p
                v-for="el in scope.row.carbonCopyUsers"
                :key="el.id"
              >
                {{ el.name }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            prop="taskStartTime"
            label="开始时间"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="taskEndTime"
            label="截止日期"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
            min-width="120"
          >
            <template slot-scope="scope">
              <p
                v-if="scope.row.remark === null"
                style="color: rgb(199, 199, 199); font-size: 0.8rem"
              >
                暂无备注
              </p>
              <p v-else>{{ scope.row.remark }}</p>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            label="附件列表"
            prop="fileInfos"
            min-width="200"
          >
            <template slot-scope="scope">
              <div
                v-if="scope.row.fileInfos.length == 0"
                style="color: rgb(199, 199, 199); font-size: 0.8rem"
              >
                暂无附件
              </div>
              <div
                v-else
                style="text-align: center"
              >
                <div
                  @click="showFile(item)"
                  class="imgHover"
                  v-for="(item, index) in scope.row.fileInfos"
                  :key="index"
                  title="点击下载"
                >
                  <img
                    style="width: 80px; height: 80px"
                    :src="item.path"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="editHandler(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                @click="deleteHanler(scope.row.id)"
                style="color: red"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row>
      <el-dialog
        title="任务设置"
        :visible.sync="taskShow"
        width="30%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form :model="taskForm">
          <el-form-item
            label="任务名称："
            label-width="90px"
          >
            <el-input
              v-model="taskForm.name"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="任务类型："
            label-width="90px"
          >
            <el-select
              style="width: 100%"
              v-model="taskForm.type"
              multiple
              placeholder="请选择任务类型"
              @change="selectType"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="任务内容："
            label-width="90px"
          >
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入任务内容"
              v-model="taskForm.content"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="任务备注："
            label-width="90px"
          >
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入任务备注"
              v-model="taskForm.remark"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="taskShow = false">取 消</el-button>
          <el-button
            type="primary"
            @click="saveSetTaskHandler"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import cardBox from './components/cardBox'
import {
  getTypeList,
  getTaskCountList,
  getTaskInfoPage,
  addTaskConfig,
  deleteTaskInfo,
} from '../../http/officeTaskMg/officeTaskMg.js'
import { downloadFile } from '../../http/commonApi.js'
import { blobToBase64 } from '../../utils/autoClick.js'
import store from '../../store/index.js'
import axios from 'axios'
export default {
  data() {
    return {
      cardBox: [
        {
          id: 1,
          title: '已完成',
          num: '35',
          differValue: '10',
          riseFall: 1,
          icon: 'el-icon-data-line',
          bgc: '#70f3ff',
          show: 0,
        },
        {
          id: 2,
          title: '待开始',
          num: '35',
          differValue: '10',
          riseFall: 0,
          icon: 'el-icon-data-line',
          bgc: '#7fecad',
          show: 0,
        },
        {
          id: 3,
          title: '进行中',
          num: '35',
          differValue: '10',
          riseFall: 1,
          icon: 'el-icon-data-line',
          bgc: '#70f3ff',
          show: 0,
        },
        {
          id: 4,
          title: '已逾期',
          num: '35',
          differValue: '10',
          riseFall: 1,
          icon: 'el-icon-data-line',
          bgc: '#7fecad',
          show: 0,
        },
      ],
      typeList: [],
      taskType: null,
      key: '',
      date: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      isSearch: false,
      taskShow: false,
      taskForm: {
        id: null,
        name: '',
        type: [],
        content: '',
        remark: '',
      },
      renderData: [],
      batchArr: [],
    }
  },
  components: {
    cardBox,
  },

  mounted() {
    getTypeList().then((res) => {
      if (res.code == 200) {
        this.typeList = res.data
        console.log(this.typeList)
      }
    })
    this.getTaskCountListApi()
    this.getTaskInfoPageApi()
  },

  methods: {
    toAddHandler() {
      this.$router.push('/addTaskList')
    },

    searchHandler() {
      this.isSearch = true
      this.getTaskCountListApi(this.date[0], this.date[1])
      this.getTaskInfoPageApi(
        1,
        this.pageSize,
        this.taskType,
        this.date[0],
        this.date[1],
        this.key
      )
    },

    NewSearch() {
      this.taskType = ''
      this.date = []
      this.key = ''
      this.pageSize = 10

      this.isSearch = true
      this.getTaskCountListApi(this.date[0], this.date[1])
      this.getTaskInfoPageApi(
        1,
        this.pageSize,
        this.taskType,
        this.date[0],
        this.date[1],
        this.key
      )
    },

    handleSelectionChange(v) {
      this.batchArr = v
    },

    handleCurrentChange(v) {
      this.pageNum = v
      if (this.isSearch == true) {
        this.getTaskInfoPageApi(
          v,
          this.pageSize,
          this.taskType,
          this.date[0],
          this.date[1],
          this.key
        )
      } else {
        this.getTaskInfoPageApi(v, this.pageSize)
      }
    },

    handleSizeChange(v) {
      this.pageNum = 1
      this.pageSize = v
      if (this.isSearch == true) {
        this.getTaskInfoPageApi(
          1,
          v,
          this.taskType,
          this.date[0],
          this.date[1],
          this.key
        )
      } else {
        this.getTaskInfoPageApi(1, v)
      }
    },

    setTask() {
      this.taskShow = true
    },

    batchExport() {
      let batchArr = ''
      this.batchArr.forEach((item, index) => {
        if (index < this.batchArr.length) {
          batchArr = batchArr + item.id + ','
        } else {
          batchArr = batchArr + item.id
        }
      })
      console.log(batchArr)
      let server = axios.create({
        baseURL: '/api',
        timeout: 5000,
      })
      server.interceptors.request.use(
        (config) => {
          config.headers.Authorization = store.state.token
          return config
        },
        (err) => {
          Promise.reject(err)
        }
      )

      server({
        method: 'get',
        url: '/task/info/export?ids=' + batchArr,
        resType: 'blob',
      }).then((res) => {
        console.log(res)
        if (res.status == 200) {
          let blob = new Blob([res], { type: 'application/xlsx' })
          let url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url

          link.click()
          URL.revokeObjectURL(url)
          this.$message.success('下载成功，请稍等')
        } else {
          this.$message({
            type: 'info',
            message: '下载失败，请联系管理员',
          })
        }
      })
    },

    saveSetTaskHandler() {
      this.addTaskConfigApi(this.taskForm)
    },

    editHandler(row) {
      this.$router.push({
        name: 'addTaskList',
        params: row,
      })
    },
    deleteHanler(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该信息?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteTaskInfo(id).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
              this.searchHandler()
            } else {
              this.$message({
                type: 'info',
                message: '删除失败，请联系管理员',
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    /**
     * 接口
     */

    getTaskCountListApi(taskStartTime = '', taskEndTime = '') {
      let params = { taskStartTime, taskEndTime }

      getTaskCountList(params).then((res) => {
        console.log('res', res)
        if (res.code == 200) {
          if (res.data.length == 1) {
            this.cardBox[0].num = res.data[0].taskInfoCount.completeCount
            this.cardBox[1].num = res.data[0].taskInfoCount.toStartedCount
            this.cardBox[2].num = res.data[0].taskInfoCount.doingCount
            this.cardBox[3].num = res.data[0].taskInfoCount.overdueCount
            this.cardBox[0].show = 1
            this.cardBox[1].show = 1
            this.cardBox[2].show = 1
            this.cardBox[3].show = 1
          } else {
            const date1 = new Date(res.data[0].date)
            const date2 = new Date(res.data[1].date)
            if (date1 > date2) {
              console.log('date1 比 date2 晚')
              this.cardBox[0].num = res.data[0].taskInfoCount.completeCount
              this.cardBox[1].num = res.data[0].taskInfoCount.toStartedCount
              this.cardBox[2].num = res.data[0].taskInfoCount.doingCount
              this.cardBox[3].num = res.data[0].taskInfoCount.overdueCount
              let differValue1 =
                res.data[0].taskInfoCount.completeCount -
                res.data[1].taskInfoCount.completeCount
              let differValue2 =
                res.data[0].taskInfoCount.toStartedCount -
                res.data[1].taskInfoCount.toStartedCount
              let differValue3 =
                res.data[0].taskInfoCount.doingCount -
                res.data[1].taskInfoCount.doingCount
              let differValue4 =
                res.data[0].taskInfoCount.overdueCount -
                res.data[1].taskInfoCount.overdueCount
              this.cardBox[0].differValue = Math.abs(differValue1)
              this.cardBox[1].differValue = Math.abs(differValue2)
              this.cardBox[2].differValue = Math.abs(differValue3)
              this.cardBox[3].differValue = Math.abs(differValue4)
              this.cardBox[0].riseFall = differValue1 >= 0 ? 1 : 0
              this.cardBox[1].riseFall = differValue2 >= 0 ? 1 : 0
              this.cardBox[2].riseFall = differValue3 >= 0 ? 1 : 0
              this.cardBox[3].riseFall = differValue4 >= 0 ? 1 : 0
            } else {
              console.log('date1 比 date2 早')
              this.cardBox[0].num = res.data[1].taskInfoCount.completeCount
              this.cardBox[1].num = res.data[1].taskInfoCount.toStartedCount
              this.cardBox[2].num = res.data[1].taskInfoCount.doingCount
              this.cardBox[3].num = res.data[1].taskInfoCount.overdueCount
              let differValue1 =
                res.data[1].taskInfoCount.completeCount -
                res.data[0].taskInfoCount.completeCount
              let differValue2 =
                res.data[1].taskInfoCount.toStartedCount -
                res.data[0].taskInfoCount.toStartedCount
              let differValue3 =
                res.data[1].taskInfoCount.doingCount -
                res.data[0].taskInfoCount.doingCount
              let differValue4 =
                res.data[1].taskInfoCount.overdueCount -
                res.data[0].taskInfoCount.overdueCount
              this.cardBox[0].differValue = Math.abs(differValue1)
              this.cardBox[1].differValue = Math.abs(differValue2)
              this.cardBox[2].differValue = Math.abs(differValue3)
              this.cardBox[3].differValue = Math.abs(differValue4)
              this.cardBox[0].riseFall = differValue1 >= 0 ? 1 : 0
              this.cardBox[1].riseFall = differValue2 >= 0 ? 1 : 0
              this.cardBox[2].riseFall = differValue3 >= 0 ? 1 : 0
              this.cardBox[3].riseFall = differValue4 >= 0 ? 1 : 0
            }
          }
        }
      })
    },

    getTaskInfoPageApi(
      pageNum = 1,
      pageSize = 5,
      taskType = null,
      taskStartTime = '',
      taskEndTime = '',
      key = ''
    ) {
      let params = {
        pageNum,
        pageSize,
        taskType,
        taskStartTime,
        taskEndTime,
        key,
      }
      console.log('params::: ', params)
      getTaskInfoPage(params).then((res) => {
        if (res.code == 200) {
          console.log('分页::: ', res)
          res.data.records.forEach((item) => {
            if (item.fileInfos.length > 0) {
              item.fileInfos.forEach((el) => {
                downloadFile({ path: el.path }).then((resImg) => {
                  blobToBase64(resImg).then((resBase64) => {
                    el.path = resBase64
                  })
                })
              })
            }
          })
          this.renderData = res.data.records
          this.total = res.data.total
        }
      })
    },

    selectType(v) {
      this.taskForm.remark = this.typeList.find((el) => {
        return el.type == v
      }).remark
    },

    addTaskConfigApi(params) {
      addTaskConfig(params).then((res) => {
        if (res.code == 200) {
          this.$message.success('设置任务成功')
          this.taskShow = true
        } else {
          this.$message.error(res.message)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.qaBox {
  width: 100%;
  height: 100%;
  .boxShadow {
    box-shadow: 1px 1px 10px rgb(184, 184, 184);
    padding: 10px;
    box-sizing: border-box;
    border-radius: 5px;
    padding: 0 8rem;
    margin-bottom: 10px;
  }
}
.tableBox {
}
</style>
